import ssl
from flask import Flask
from flask_socketio import SocketIO, emit
from flask_cors import CORS
from get_config.index import config

socket_app = Flask(__name__)

CORS(socket_app, supports_credentials=True)
socketio_app = SocketIO(socket_app, cors_allowed_origins=config["socket_origins"])


@socketio_app.on('message')
def handle_message(message):
    print(message)
    emit('message', message, broadcast=True)


def run_socketio_app(debug):
    if debug:
        socket_app.debug = debug
    if config["socket_is_ssl"]:
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(config["crt"], config["key"])
        socketio_app.run(socket_app, host=config["ssl_host"], port=config["socket_port"], ssl_context=context, allow_unsafe_werkzeug=True)
    else:
        socketio_app.run(socket_app, config["socket_host"], config["socket_port"], allow_unsafe_werkzeug=True)


if __name__ == '__main__':
    run_socketio_app(False)
